//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

use df_proto_gen_rust::config_api::config_api_client::ConfigApiClient;
use df_proto_gen_rust::config_api::*;
use tauri::{
    plugin::{Plugin, Result as PluginResult},
    AppHandle, Invoke, PageLoadPayload, Runtime, Window,
};

#[tauri::command]
async fn get_data_ttl(
    addr: String,
    request: GetDataTtlRequest,
) -> Result<GetDataTtlResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.get_data_ttl(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn get_port_info(
    addr: String,
    request: GetPortInfoRequest,
) -> Result<GetPortInfoResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.get_port_info(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn get_auth_check_state(
    addr: String,
    request: GetAuthCheckStateRequest,
) -> Result<GetAuthCheckStateResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.get_auth_check_state(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn enable_auth_check(
    addr: String,
    request: EnableAuthCheckRequest,
) -> Result<EnableAuthCheckResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.enable_auth_check(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn disable_auth_check(
    addr: String,
    request: DisableAuthCheckRequest,
) -> Result<DisableAuthCheckResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.disable_auth_check(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn add_auth_secret(
    addr: String,
    request: AddAuthSecretRequest,
) -> Result<AddAuthSecretResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.add_auth_secret(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn remove_auth_secret(
    addr: String,
    request: RemoveAuthSecretRequest,
) -> Result<RemoveAuthSecretResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.remove_auth_secret(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn update_auth_secret(
    addr: String,
    request: UpdateAuthSecretRequest,
) -> Result<UpdateAuthSecretResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.update_auth_secret(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn get_auth_secret(
    addr: String,
    request: GetAuthSecretRequest,
) -> Result<GetAuthSecretResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.get_auth_secret(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

#[tauri::command]
async fn list_auth_secret(
    addr: String,
    request: ListAuthSecretRequest,
) -> Result<ListAuthSecretResponse, String> {
    let chan = crate::conn_extern_server(addr).await;
    if chan.is_err() {
        return Err(chan.err().unwrap());
    }
    let mut client = ConfigApiClient::new(chan.unwrap());
    match client.list_auth_secret(request).await {
        Ok(response) => {
            let inner_resp = response.into_inner();
            return Ok(inner_resp);
        }
        Err(status) => Err(status.message().into()),
    }
}

pub struct ConfigApiPlugin<R: Runtime> {
    invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync + 'static>,
}

impl<R: Runtime> ConfigApiPlugin<R> {
    pub fn new() -> Self {
        Self {
            invoke_handler: Box::new(tauri::generate_handler![
                get_data_ttl,
                get_port_info,
                get_auth_check_state,
                enable_auth_check,
                disable_auth_check,
                add_auth_secret,
                remove_auth_secret,
                update_auth_secret,
                get_auth_secret,
                list_auth_secret,
            ]),
        }
    }
}

impl<R: Runtime> Plugin<R> for ConfigApiPlugin<R> {
    fn name(&self) -> &'static str {
        "dragonfly_config_api"
    }
    fn initialization_script(&self) -> Option<String> {
        None
    }

    fn initialize(&mut self, _app: &AppHandle<R>, _config: serde_json::Value) -> PluginResult<()> {
        Ok(())
    }

    fn created(&mut self, _window: Window<R>) {}

    fn on_page_load(&mut self, _window: Window<R>, _payload: PageLoadPayload) {}

    fn extend_api(&mut self, message: Invoke<R>) {
        (self.invoke_handler)(message)
    }
}